package com.ming_za.od_updater.core.updater.handler;

import com.ming_za.od_updater.core.updater.UpdateState;
import com.ming_za.od_updater.core.window.page.FailPage;
import com.ming_za.od_updater.core.window.LoadingState;
import com.ming_za.od_updater.core.updater.StateBridge;
import com.ming_za.od_updater.core.window.PageManager;
import com.ming_za.od_updater.core.window.page.UpdatePage;
import com.ming_za.od_updater_sdk.ODUpdater;
import com.ming_za.od_updater_sdk.event.PostUpdateEvent;
import com.ming_za.od_updater_sdk.event.UpdateCompleteEvent;
import com.ming_za.od_updater_sdk.event.UpdateStartEvent;
import com.ming_za.od_updater_sdk.handler.DefaultUpdaterHandler;
import com.ming_za.od_updater_sdk.obj.Res;

import java.util.List;

public class ModUpdateHandle extends DefaultUpdaterHandler {

    @Override
    public void updateStart(UpdateStartEvent event, ODUpdater odUpdater) {
        super.updateStart(event, odUpdater);

        int total = 0;

        for (List<Res> resList : event.getNeedUpdate().values()){
            total += resList.size();
        }

        StateBridge.setTotal(total);
        StateBridge.setCompleted(0);

        if (!event.getNeedUpdate().isEmpty()){
            PageManager.setPage(new UpdatePage());
        }

    }

    @Override
    public void postUpdate(PostUpdateEvent event) {
        super.postUpdate(event);
        StateBridge.addCompleted();
    }

    @Override
    public void allUpdateComplete(UpdateCompleteEvent event) {
        super.allUpdateComplete(event);
        if (event.hasError()){
            StateBridge.setUpdateState(UpdateState.FAILED);
            PageManager.setPage(new FailPage());
        }else {
            StateBridge.setLoadingState(LoadingState.CONTINUE);
        }
    }
}
